//
//  AddressBookController.swift
//  Alamofire
//
//  Created by 易先生 on 2022/8/26.
//

import UIKit
import Contacts
import EarbudsDatabase

class AddressBookController: ViewController {

    let viewModel = AddressBookViewModel()

	override func makeUI() {
		super.makeUI()

        view.backgroundColor = R.color.common_10_bg_page()
        navigation.item.title = R.string.localizable.setting_contacts_text()
		reloadTableViewData()
		navigationItem.leftBarButtonItem = leftBarButtonItem
		view.addSubview(titleLabel)
		view.addSubview(tableView)
		view.addSubview(noDataView)
        view.addSubview(bottomProgressView)

        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(kNavHeight+10)
            make.leading.equalToSuperview().offset(10)
            make.centerX.equalToSuperview()
		}

		noDataView.snp.makeConstraints { make in
            make.top.equalToSuperview()
			make.leading.trailing.equalToSuperview()
			make.bottom.equalToSuperview()
		}

        bottomProgressView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
        }

		tableView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
			make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(bottomProgressView.snp.top)
		}
	}

	private func reloadTableViewData() {
		noDataView.isHidden = true
        bottomProgressView.isHidden = false
		footView.isHidden = false
        rightBarButtonItem.tintColor = R.color.common_27_main_color()
		self.navigation.item.rightBarButtonItem = rightBarButtonItem
		if viewModel.items.count <= 0 {
			navigationItem.rightBarButtonItem = nil
			noDataView.isHidden = false
            bottomProgressView.isHidden = true
			footView.isHidden = true
			rightBarButtonItem.tintColor = .clear
		}
		if viewModel.items.count >= 8 {
			self.footView.isHidden = true
		}
        self.bottomProgressView.completeBookButton.isEnabled = viewModel.isModified()
		self.tableView.reloadData()
	}

	override func bindViewModel() {
		super.bindViewModel()
                
        viewModel.maxCount.subscribe(onNext: { [weak self] num in
            guard let self = self else { return }
            self.titleLabel.attributedText = R.string.localizable.setting_contact_hint("\(num)").toAttributed
                .font(Fonts.systemFont(ofSize: 14))
                .foregroundColor(R.color.common_23_text_second())
                .paragraph(setup: { style in
                    style.lineSpacing = 3
                    style.lineBreakMode = .byTruncatingTail
                }).rawValue
            
            self.noDataView.configIconWithTitle(icon: "img_contacts_none",
                                           title: R.string.localizable.setting_contact_add(),
                                           desc: R.string.localizable.setting_contact_hint("\(num)"))
            reloadTableViewData()
        }).disposed(by: rx.disposeBag)

		noDataView.addAddressBookButton.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }
			self.pushSelectController(editContact: nil)
		}.disposed(by: rx.disposeBag)

		rightBarButtonItem.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }

			let status = CNContactStore.authorizationStatus(for: .contacts)
			if status == .authorized {
				self.pushSelectController(editContact: nil, isEditAll: true)
			} else if status == .notDetermined {
				CNContactStore().requestAccess(for: .contacts) { (_, _) in
				}
			} else {
				self.showAuthorityTip()
			}
		}.disposed(by: rx.disposeBag)

		footView.addButton.rx.tap.subscribe { [weak self] _ in
			guard let self = self else { return }
			self.pushSelectController(editContact: nil)
		}.disposed(by: rx.disposeBag)
        
        viewModel.itemsRelay.subscribe(onNext: { [weak self] _  in
            guard let `self` = self else { return }
            self.reloadTableViewData()
        }).disposed(by: rx.disposeBag)
	}

	private func pushSelectController(editContact: ContactModel?, isEditAll: Bool = false) {
		let vc = SelectContactController()
        vc.editContact = editContact
		navigationController?.pushViewController(vc, animated: true)

		if isEditAll == false {
			vc.currentSelectContact = self.viewModel.items
			vc.oldSelectCount = self.viewModel.items.count
		}

		vc.selectContactRelay.subscribe(onNext: { [weak self] contacts in
			guard let self = self else { return }
			self.viewModel.addContacts(models: contacts)
		}).disposed(by: rx.disposeBag)
	}

    @objc private func save() {
        if BluetoothManager.shared.isConnected {
            if let batteryInfoModel = BluetoothManager.shared.receiveBatteryInfo.value {
                if batteryInfoModel.boxBattery <= UpgradeFuncMinBattaryLimit  {
                    self.view.makeToast(R.string.localizable.setting_contact_electric_low_tip(), duration: 2.0, position: .center)
                } else {
                    self.viewModel.sendContact()
                    self.view.makeToast(R.string.localizable.setting_contact_upload_success(), duration: 2.0, position: .top)
                    self.reloadTableViewData()
                }
            }
        }
	}

	private func showAuthorityTip() {
        let alertController = UIAlertController(title: nil, message: R.string.localizable.setting_contact_permission_hint(), preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: R.string.localizable.common_cancel(), style: .cancel, handler: nil)
		let settingAction = UIAlertAction(title: R.string.localizable.common_finished(), style: UIAlertAction.Style.default, handler: { _ in
            if let url = URL(string: UIApplication.openSettingsURLString) {
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url)
                }
            }
			
		})
		alertController.addAction(cancelAction)
		alertController.addAction(settingAction)
		self.present(alertController, animated: true, completion: nil)
	}

	private lazy var rightBarButtonItem: UIBarButtonItem = {
		let rightBarButtonItem = UIBarButtonItem()
        rightBarButtonItem.title = R.string.localizable.setting_contact_edit_all()
        rightBarButtonItem.tintColor = R.color.common_27_main_color()
		return rightBarButtonItem
	}()

	private lazy var leftBarButtonItem: UIBarButtonItem = {
        let leftBarButtonItem = UIBarButtonItem(image: R.image.ic_common_nav_back(), style: .plain, target: self, action: #selector(backAction))
		return leftBarButtonItem
	}()
    
    private lazy var titleLabel: Label = {
        let label = Label()
        label.textColor = R.color.common_23_text_second()
        label.font = Fonts.systemFont(ofSize: 12)
        label.numberOfLines = 0
        label.backgroundColor = .clear
        return label
    }()
    
	private lazy var noDataView: AddressBookNoDataView = {
		let noDataView = AddressBookNoDataView()
		noDataView.isHidden = true
        noDataView.backgroundColor = R.color.common_2_bg_page()
		return noDataView
	}()

	private lazy var footView: AddFootView = {
		let footView = AddFootView.init(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 60))
		return footView
	}()

	private lazy var tableView: JXMovableCellTableView = {
		let tableView = JXMovableCellTableView(frame: .zero, style: .plain)
        tableView.backgroundColor = R.color.common_2_bg_page()
		tableView.estimatedRowHeight = 50
		tableView.rowHeight = UITableView.automaticDimension
        tableView.separatorColor = R.color.common_6_line()
		tableView.jxDelegate = self
		tableView.jxDataSource = self
		tableView.delegate = self
		tableView.dataSource = self
		tableView.longPressGesture.minimumPressDuration = 0.5
		tableView.tableFooterView = footView
		tableView.register(FriendCell.self, forCellReuseIdentifier: FriendCell.reuseIdentifier)
		return tableView
	}()
    
    public lazy var bottomProgressView: AddressBookProgressView = {
        let bottomProgressView = AddressBookProgressView()
        bottomProgressView.backgroundColor = R.color.common_2_bg_page()
        bottomProgressView.completeBookButton.addTarget(self, action: #selector(save), for: .touchUpInside)
        return bottomProgressView
    }()
}

extension AddressBookController: JXMovableCellTableViewDataSource, UITableViewDataSource {

	func dataSourceArrayInTableView(_ tableView: JXMovableCellTableView) -> [Any] {
		return viewModel.items
	}

	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return viewModel.numberOfRowsInSection()
	}

	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		let model = viewModel.cellModelForRowAtIndexPath(indePath: indexPath)
		let cell = tableView.dequeueReusableCell(withIdentifier: FriendCell.reuseIdentifier) as! FriendCell
		cell.configModel(model: model)
		return cell

	}

	func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
		viewModel.removeCardModel(indexPath: indexPath)
	}

	func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
		return true
	}

	func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
		viewModel.moveRowAt(fromIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath)
	}
}

extension AddressBookController: JXMovableCellTableViewDelegate, UITableViewDelegate {

	func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
		return .delete
	}

	func tableView(_ tableView: JXMovableCellTableView, customizeStartMovingAnimation movableCellsnapshot: UIImageView, fingerPoint: CGPoint) {
		UIView.animate(withDuration: 0.25) {
			movableCellsnapshot.center = CGPoint(x: movableCellsnapshot.center.x, y: fingerPoint.y)
		}
	}

	func tableView(_ tableView: JXMovableCellTableView, customizeMovalbeCell movableCellsnapshot: UIImageView) {
//		movableCellsnapshot.layer.shadowColor = UIColor.red.cgColor
//		movableCellsnapshot.layer.masksToBounds = false
//		movableCellsnapshot.layer.cornerRadius = 0
//		movableCellsnapshot.layer.shadowOffset = .zero
//		movableCellsnapshot.layer.shadowOpacity = 0.4
//		movableCellsnapshot.layer.shadowRadius = 10
	}

	func tableView(_ tableView: JXMovableCellTableView, willMoveCellAtIndexPath indexPath: IndexPath) {
	}

	func tableView(_ tableView: JXMovableCellTableView, didMoveCellFromIndexPath fromIndexPath: IndexPath, toIndexPath: IndexPath) {
	}

	func tableView(_ tableView: JXMovableCellTableView, endMoveCellAtIndexPath indexPath: IndexPath) {
	}

	func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		let model = viewModel.cellModelForRowAtIndexPath(indePath: indexPath)
		self.pushSelectController(editContact: model)
	}
}
